package framework.bean.factory;

import framework.dao.exception.DataAccessException;
import framework.dao.mybatis.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.io.*;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

public class ObjectFactory {

    private static Map<String,Object> objects=new HashMap<String,Object>();

    static {

        BufferedReader br=null;
        try{

            br=new BufferedReader(
                    new InputStreamReader(
                            ObjectFactory.class
                                         .getClassLoader()
                                         .getResourceAsStream("objects.cfg")));

            String s=null;

            while ((s=br.readLine())!=null){
                String[] entry=s.split("=");

                //如果是dao
                if("mybatisDao".equals(entry[0])){
                    //从SqlSession中获得
                    String realPath=ObjectFactory.class.getClassLoader().getResource("").getPath();


                    File dir=new File(realPath+entry[1].replace(".",File.separator));

                    File[] files=dir.listFiles(new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String name) {
                            return name.endsWith(".class");
                        }
                    });

                    for (File file : files) {
                        String daoClassName=entry[1]+"."+file.getName().substring(0,file.getName().lastIndexOf(".class"));


                        Class daoClass=Class.forName(daoClassName);

                        String key=daoClass.getSimpleName();

                        String firstChar=key.charAt(0)+"";

                        key=firstChar.toLowerCase()+key.substring(1);


                        objects.put(key,daoClass);
                    }


                    continue;
                }

                objects.put(entry[0],Class.forName(entry[1]).newInstance());
            }



        }catch (Exception e){
            e.printStackTrace();
            throw new ExceptionInInitializerError("ObjectFactory初始化失败");
        }finally{
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

    public static Object getObject(String key){


        Object object=objects.get(key);

        System.out.println("object = " + object);

        if(object instanceof Class) {


            Class daoClass=(Class)object;

            SqlSession session = MyBatisUtil.getSession();
            Object daoObject = session.getMapper(daoClass);


            Object daoProxy = Proxy.newProxyInstance(daoObject.getClass().getClassLoader(),
                    new Class[]{daoClass},
                    new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                            Object result = null;

                            try {

                                result = method.invoke(daoObject, args);


                            } catch (Exception e) {
                                throw new DataAccessException("数据访问失败", e);
                            }


                            return result;
                        }
                    });

            return daoProxy;

        }
        return object;
    }



}
